package demo7;

/**
 * 单链表的归并排序
 */
public class Main1 {
    public static void main(String[] args) {
        ListNode head = new ListNode(5);
        head.next = new ListNode(3);
        head.next.next = new ListNode(8);
        head.next.next.next = new ListNode(1);
        head.show();
        mergeSort(head).show();
    }

    public static ListNode mergeSort(ListNode head){
        if(head == null || head.next == null) return head;

        ListNode secondList = splitList(head);
        return merge(mergeSort(head),mergeSort(secondList));
    }


    // 把链表一份为二
    public static ListNode splitList(ListNode head){
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next!=null && fast.next.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode secondList = slow.next;
        slow.next = null;
        return secondList;
    }

    // 合并两个有序链表
    public static ListNode merge(ListNode p1,ListNode p2){
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;
        while(p1!=null&&p2!=null){
            if(p1.val <= p2.val){
                p.next = p1;
                p1 = p1.next;
            }else{
                p.next = p2;
                p2 = p2.next;
            }
            p = p.next;
        }
        if(p1!=null) p.next = p1;
        if(p2!=null) p.next = p2;
        return dummy.next;
    }

}
class ListNode{

    int val;
    ListNode next;
    ListNode(int val){
        this.val = val;
    }

    void show(){
        ListNode p = this;
        while(p!=null){
            System.out.print(p.val +" ");
            p = p.next;
        }
        System.out.println();
    }

}